﻿using JinShun.OA.UI.Apis;
using JinShun.OA.UI.Dtos;
using JinShun.OA.UI.Urls;
using Microsoft.AspNetCore.Components.Authorization;
using System.Security.Claims;


namespace JinShun.OA.UI.Auth
{
    public class AntSKAuthProvider : AuthenticationStateProvider
    {
        private readonly HttpWebClient http;
        public AntSKAuthProvider(HttpWebClient _http)
        {
            this.http = _http;
        }


        private ClaimsIdentity identity = new ClaimsIdentity();
        public async Task<RequesResult> SignIn(LoginInputDto vo)
        {
            RequesResult strresult = await http.ExecuteAsync(UrlBases.Login_Reques, HttpMethod.Post, Newtonsoft.Json.JsonConvert.SerializeObject(vo), null);
            if (strresult.GetRequesCode() == 0)
            {
                var result = strresult.GetData<SystemTokenDto>();
                if (result != null)
                {
                    //获取登陆的信息
                    Dictionary<string, string> headers = new Dictionary<string, string>();
                    headers.Add("Authorization", "Bearer " + result.Token);
                    UserRoleMenuDto result1 = await http.GetAsync<UserRoleMenuDto>(UrlBases.LoginInfo_Reques, headers);
                    if (result1 == null || result1.User.Name == null) return RequesResult.error();
                    string AdminRole = result1.User.Name;
                    var claims = new[] {
                            new Claim(ClaimTypes.Name, result1.User.UserName),
                            new Claim(ClaimTypes.Role, result1.RoleCodes[0]),
                            new Claim(ClaimTypes.Sid,result.Token),
                            new Claim(ClaimTypes.Rsa,result1.User.Id.ToString())
                        };
                    identity = new ClaimsIdentity(claims, AdminRole);
                    NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
                }
            }
            return strresult;
        }
        public ClaimsPrincipal GetCurrentUser()
        {
            var user = new ClaimsPrincipal(identity);
            return user;
        }
        public override async Task<AuthenticationState> GetAuthenticationStateAsync()
        {
            var user = new ClaimsPrincipal(identity);
            return await Task.FromResult(new AuthenticationState(user));
        }
    }
}
